package CompletableFuture_14;

import java.util.concurrent.*;
import java.util.function.*;

public class 复杂工作流示例 {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 第一阶段任务 - 使用Supplier
        CompletableFuture<Integer> userIdFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            public Integer get() {
                try {
                    Thread.sleep(200);
                    return 12345;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, executor);

        // 第二阶段任务 - 并行获取信息
        CompletableFuture<String> userInfoFuture = userIdFuture.thenApplyAsync(new Function<Integer, String>() {
            public String apply(Integer userId) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return "用户" + userId + "信息";
            }
        }, executor);

        CompletableFuture<String> orderInfoFuture = userIdFuture.thenApplyAsync(new Function<Integer, String>() {
            public String apply(Integer userId) {
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return "用户" + userId + "的订单";
            }
        }, executor);

        // 组合结果
        CompletableFuture<String> combinedFuture = userInfoFuture.thenCombine(
                orderInfoFuture,
                new BiFunction<String, String, String>() {
                    public String apply(String userInfo, String orderInfo) {
                        return userInfo + " + " + orderInfo;
                    }
                });

        combinedFuture.thenAccept(new Consumer<String>() {
            public void accept(String combinedResult) {
                System.out.println("最终结果: " + combinedResult);
            }
        }).get();

        executor.shutdown();
    }
}